package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.network.NetDataJson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class RankCarActivity extends BaseActivity implements OnClickListener, AbsListView.OnItemClickListener, NetDataJson.OnNetDataJsonListener,
        OnRefreshListener<ListView>, OnLastItemVisibleListener {

    private PullToRefreshListView pullToRefreshListView;

    private ListView listView;

    private CarSourceListAdapter carSourceAdapter;

    private int pageIndex;

    private boolean isLoadingMore;

    private boolean hasMore;

    private List<CarSource> carSourceDataList;

    private NetDataJson netWork;

    private boolean isRefresh = true;

    // request network need item:
    private String brand = "", model = "", sort = "";// use

    private TextView titleT;

    private String cityName = "北京";

    private ImageView  noinfo;

    private View footView;

    private boolean isBrand = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            brand = bundle.getString("brandSlug", "");
            model = bundle.getString("modelSlug", "");
            isBrand = bundle.getBoolean("isBrand", false);
            cityName = bundle.getString("location", MainActivity.main.currentCity);
            if (!isBrand)
                action = "buy_billboard_sameModel";
            else
                action = "buy_billboard_sameBrand";
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rank_carlist_fragment);
        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        initView();
    }


    private void initView() {



        noinfo = (ImageView) findViewById(R.id.no_info);
        netWork = new NetDataJson(this);
        titleT = (TextView) findViewById(R.id.top_title);
        if (!isBrand)
            titleT.setText("同款列表");
        else
            titleT.setText("同品牌列表");



        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);

        pullToRefreshListView.setOnLastItemVisibleListener(this);

        carSourceDataList = new ArrayList<CarSource>();

        pageIndex = 1;
        isLoadingMore = true;
        hasMore = true;

        carSourceAdapter = new CarSourceListAdapter(this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(carSourceAdapter);
        listView.setOnItemClickListener(this);

        listView.removeFooterView(footView);
        carSourceAdapter.notifyDataSetChanged();


        listView.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 200);

    }


    // 加载更多
    private void LoadMoreData() {

        if (!hasMore) {
            Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isLoadingMore && hasMore && carSourceDataList.size() > 0) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            isLoadingMore = true;
            pageIndex++;
            updateData();
        }
    }


    private void updateData() {

        netWork.setUrl(API.carListSearch);
        netWork.addParam("city", cityName);
        netWork.addParam("page", pageIndex);
        if (brand != null)
            netWork.addParam("brand", brand);
        if (model != null)
            netWork.addParam("model", model);
        if (sort != null)
            netWork.addParam("sort", sort);

        netWork.request("get");

    }


    // 重新获取数据
    private void onUpdateData() {
        noinfo.setVisibility(View.GONE);
        isRefresh = true;
        pageIndex = 1;
        hasMore = true;
        updateData();
    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (netWork != null) {
            netWork.cancelTask();
        }
    }

    @Override
    public void onLastItemVisible() {
        LoadMoreData();
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        onUpdateData();
    }



    @Override
    public void onDataJsonError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        isLoadingMore = false;
        pullToRefreshListView.onRefreshComplete();

    }


    @Override
    public void onDataJsonUpdate(JSONObject json) {
        JSONArray jsonArray = null;
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        if (isRefresh) {
            carSourceDataList.clear();
            carSourceAdapter.notifyDataSetChanged();
        }
        try {
            jsonArray = json.getJSONArray("car_list");
            if (0 == jsonArray.length()) {
                noinfo.setVisibility(View.VISIBLE);
                isLoadingMore = false;
                Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();
                pullToRefreshListView.onRefreshComplete();
                return;
            }
            getDataFromJsonArray(jsonArray);

            int page_num = json.getInt("page_num");
            if (page_num == pageIndex) {
                hasMore = false;
            }

        } catch (JSONException e) {
            Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();
            isLoadingMore = false;
            pullToRefreshListView.onRefreshComplete();
            return;
        }

        updateListView();
    }


    private void updateListView() {
        if (carSourceDataList.size() != 0) {
            carSourceAdapter.setData(carSourceDataList);
            pullToRefreshListView.onRefreshComplete();
            isLoadingMore = false;
        } else {
            noinfo.setVisibility(View.VISIBLE);
        }
    }


    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        // Log.e("getDataFromJsonArray", "getDataFromJsonArray");
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);
            carSrc.mCity = cityName;
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = object.getString("time");
            carSrc.hasmodel = object.getString("has_model_detail");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            // carSrc.mRecommend = object.getString("recommend");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");
            carSrc.origin_price = object.getString("origin_price");
            carSrc.lowest_price = object.getString("lowest_price");
            carSrc.last_price = object.getString("last_price");
            carSrc.setBrand(object.getString("brand_slug"));
            carSrc.setModel(object.getString("model_slug"));
            carSrc.cs_clean = object.getBoolean("cs_clean");
            carSrc.isactive = object.getBoolean("seller_active");
            carSrc.mUrl = carSrc.mThumbnail;
            carSourceDataList.add(carSrc);
        }
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Intent intent = new Intent();
        intent.setClass(this, CarBuyDetailActivity.class);
        CarSource carSource = (CarSource) arg1.getTag(R.id.tag_second);
        intent.putExtra("typevalue", String.valueOf(carSource.mId));
        intent.putExtra("type", CarListFragment.FROM_Hot);
        intent.putExtra("from", "bestsell");
        startActivity(intent);
    }


//    @Override
//    public void getCar(String sort) {
//        this.sort = sort;
//        pullToRefreshListView.setRefreshing();
//    }
}
